package com.org.qrtrace.controller;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.org.qrtrace.Entry.request.UpdateArrivedRequest;
import com.org.qrtrace.Entry.response.ProductHistory;
import com.org.qrtrace.pojo.Checkhistory;
import com.org.qrtrace.pojo.Phistory;
import com.org.qrtrace.pojo.Product;
import com.org.qrtrace.service.ICheckhistoryService;
import com.org.qrtrace.service.IPhistoryService;
import com.org.qrtrace.service.IProductService;
import com.org.qrtrace.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bonnie
 * @since 2023-03-18
 */
@RestController
@RequestMapping("/history")
@Api(tags = "溯源记录api")
public class PhistoryController {
    private final Logger logger = LoggerFactory.getLogger(PhistoryController.class);

    @Autowired
    private IPhistoryService service;
    @Autowired
    private ICheckhistoryService checkhistoryService;
    @Autowired
    private IProductService productService;

    @GetMapping("lists")
    public JsonResult<?> getList() {
        List<Phistory> phistoryList = service.list();
        List<ProductHistory> response = new ArrayList<>();
        return getJsonResult(response, phistoryList);
    }

    @PostMapping("delete")
    public JsonResult<?> removeHistory(Phistory phistory){
        QueryWrapper<Phistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("puid", phistory.getPuid());
        queryWrapper.eq("cuid", phistory.getCuid());
        if(service.remove(queryWrapper)){
            return JsonResult.success();
        }else {
            return JsonResult.fail("删除失败！");
        }
    }

    @GetMapping("getListById")
    public JsonResult<?> getListById(Product product){
        List<ProductHistory> response = new ArrayList<>();
        QueryWrapper<Phistory> wrapper = new QueryWrapper<>();
        wrapper.eq("puid",product.getPuid());
        wrapper.orderByAsc("create_time");
        List<Phistory> phistories = service.list(wrapper);
        return getJsonResult(response, phistories);
    }

    private JsonResult<?> getJsonResult(List<ProductHistory> response, List<Phistory> phistories) {
        for(Phistory item : phistories){
            Checkhistory checkhistory = checkhistoryService.getById(item.getCuid());
            Product product = productService.getById(item.getPuid());
            ProductHistory history = new ProductHistory();
            setHistoryResponse(history, item);
            if(product!=null) {
                history.setPName(product.getPName());
            }else {
                history.setPName("N/A");
            }
            if(checkhistory!=null){
                history.setIsPass(checkhistory.getIsPass());
            }else {
                history.setIsPass("0");
            }
            response.add(history);
        }
        return JsonResult.successInfo(response);
    }

    @GetMapping("/getData")
    public JsonResult<?> getData(Product product){
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.like("p_name",product.getPName());
        List<Product> list = productService.list(wrapper);
        if(list.size()>0){
            List<ProductHistory> res = new ArrayList<>();
            for(Product pro:list){
                QueryWrapper<Phistory> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("puid",pro.getPuid());
                List<Phistory> phistories = service.list(wrapper1);
                for (Phistory item:phistories) {
                    ProductHistory history = new ProductHistory();
                    Checkhistory checkhistory = checkhistoryService.getById(item.getCuid());
                    setHistoryResponse(history, item);
                    history.setPName(pro.getPName());
                    logger.info("check history:"+JSON.toJSONString(checkhistory));
                    if(checkhistory!=null){
                        history.setIsPass(checkhistory.getIsPass());
                    }else {
                        history.setIsPass("0");
                    }
                    logger.info("res:"+JSON.toJSONString(history));
                    res.add(history);
                }
            }
            return JsonResult.successInfo(res.toArray());
        }else {
            return JsonResult.fail("未查询到相关数据！");
        }
    }

    @PostMapping("/updateArrived")
    public JsonResult<?> updateArrived(UpdateArrivedRequest product){
        QueryWrapper<Phistory> wrapper = new QueryWrapper<>();
        wrapper.eq("puid",product.getPuid());
        wrapper.eq("next_source",product.getAddress());
        wrapper.select().orderByDesc("create_time");
        wrapper.last("limit 1");
        Phistory phistory = service.getOne(wrapper);
        if(phistory==null){
            return JsonResult.fail("未查询到该条数据溯源历史！");
        }
        phistory.setArrived(product.getArrived());
        logger.info(JSON.toJSONString(phistory));

        QueryWrapper<Phistory> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("puid",phistory.getPuid());
        updateWrapper.eq("cuid",phistory.getCuid());
        if(service.update(phistory,updateWrapper)){
            return JsonResult.success();
        }else {
            return JsonResult.fail("操作失败！");
        }
    }

    private void setHistoryResponse(ProductHistory history, Phistory item) {
        history.setPuid(item.getPuid());
        history.setArrived(item.getArrived());
        history.setCreateTime(item.getCreateTime());
        history.setCuid(item.getCuid());
        history.setType(item.getType());
        history.setLastSource(item.getLastSource());
        history.setNextSource(item.getNextSource());
        history.setMark(item.getMark());
    }
}
